package com.hey.mib;

import net.percederberg.mibble.Mib;
import net.percederberg.mibble.MibSymbol;
import net.percederberg.mibble.MibTypeSymbol;
import net.percederberg.mibble.MibValueSymbol;

import java.io.File;
import java.util.List;
import java.util.Set;

import static com.hey.mib.Constant.*;

/**
 * Created by heer on 2018/7/30.
 */
public class EntityGenerator {

    private String packageName;//包名
    private String savePath;//类文件存储路径

    public EntityGenerator() {
    }

    public EntityGenerator(String packageName, String savePath) {
        this.packageName = packageName;
        this.savePath = savePath;
    }

    public void generateEntity(String mibName,String oid){
        try {
            StringBuilder sb = new StringBuilder("package ");
            oid = MibUtil.getOID(oid);
            //1.加载mib文件
            Mib mib = MibUtil.loadMib(mibName);
            MibValueSymbol symbol = mib.getSymbolByOid(oid);
            //2.构造字符串
            sb.append(packageName+";\r\n");//包
            sb.append(MibUtil.getNotesString());//注释
            sb.append("import org.snmp4j.smi.*;\r\n");//smi
            sb.append("import java.util.Map;\r\n");//Map
            sb.append("import java.util.List;\r\n");//Map
            sb.append("import java.util.LinkedHashMap;\r\n");//LinkedHashMap
            String className = MibUtil.getClassNameBySymbolName(symbol);
            sb.append("public class "+MibUtil.turnFirstUp(className)+" implements "+BASIC_ENTITY_STRING+"{\r\n");//类名
            List<String> list = MibUtil.getColumns(symbol);
            sb.append(MibUtil.getColumnsString(list));//属性和set，get方法
            sb.append(MibUtil.getOidString(oid));//重写父类的getMappingOID()方法
            sb.append(MibUtil.getToString(list));//toString()方法
            sb.append(MibUtil.getIndexCount(symbol));//getIndexCount()方法
            List<String> indexString = MibUtil.getIndex(symbol);
            sb.append(MibUtil.getIndexString(indexString));//获取索引
            sb.append(MibUtil.getValueString(indexString));//获取值
            sb.append(MibUtil.getIndexValueString(indexString));//获取索引值
            sb.append(MibUtil.getSetValueString(list,className));//设置值
            sb.append("}");
            MibUtil.write(savePath,className,sb.toString());
            System.out.println("the code is generated success for mib file "+mib.getName()+",the oid is "+oid+" and the java file is located on "+savePath+MibUtil.turnFirstUp(className)+JAVA_FILE_SUFFIX);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        String mibFilePath = "D:\\mine\\snmp-demo\\src\\main\\resources\\mibs\\OPHYLINK-SYSTEM-MIB.my";
        String oid = "1.3.6.1.4.1.42861.2.1.3.2.1";
        EntityGenerator generator = new EntityGenerator(PACKET_NAME,SAVE_PATH);
        generator.generateEntity(mibFilePath,oid);
    }
}
